<script setup lang="ts">
import { reactive, onMounted } from 'vue';
import {
  getCurrentInstance,
  navigateTo,
  reLaunch,
  setNavigationBarTitle,
  showLoading,
  eventCenter,
} from '@tarojs/taro';
import {
  DELIVER_ORDER_STATUS,
  DELIVER_ORDER_STATUS_COLOR,
  DELIVER_ORDER_STATUS_BG_COLOR,
} from '/@/common/constant';
import {
  QUERY_APP_WO_DELIVER_LIST,
  COUNT_APP_STATUS_QUANTITY,
} from '/@/api/modules/deliver/app-wo-deliver';
import { LOGIN_APP } from '/@/api/modules/base/app-sys-user';
import IMG_ICON_DELIVER_ROB from '/@/assets/image/icon/deliver-rob.png';
import IMG_ICON_SPEED from '/@/assets/image/icon/speed.png';
import IMG_ICON_DELIVER_ROB_TAB_TITLE from '/@/assets/image/icon/deliver-rob-tab-title.png';
import { formatSeconds } from '/@/utils/time';
import dayjs from 'dayjs';
/**
 * 页面类型
 */
const pageTypeObj = {
  default: '我的工单',
  'report-history': '运送申请',
};

/**
 * @description 当前路由信息
 */
const params = getCurrentInstance().router?.params as {
  /**
   * 页面类型
   * - default 默认工单列表
   * - report-history 历史工单
   */
  pageType: keyof typeof pageTypeObj;
};

const state = reactive<{
  /**
   * 当前页
   */
  activePage: number;
  /**
   * 加载状态
   */
  loading: boolean;
  /**
   * 加载完成状态
   */
  finished: boolean;
  /**
   * 发起人ID
   */
  releaseUserId?: string;
  /**
   * 列表
   */
  list: AppWoDeliver.Dto[];
  /**
   * 接单状态
   * 待处理statusList参数固定是deliver_task_assign和deliver_task_receive
   * 处理中statusList参数固定是task_start、task_end和task_confirm
   * 完成statusList参数固定是task_complete
   */
  statusQuantity: {
    label: string;
    key: string;
  }[];
  /**
   * 当前工单状态
   */
  activeStatus?: string;
  /**
   * 创建时间开始 格式毫秒
   */
  createTimeBegin?: number;
  /**
   * 创建时间结束 格式毫秒
   */
  createTimeEnd?: number;
  /**
   * 创建时间筛选气泡弹出框是否显示
   */
  createTimeFilterPopoverVisible?: boolean;
}>({
  activePage: 1,
  loading: false,
  finished: false,
  releaseUserId: '',
  list: [],
  statusQuantity: [
    { label: '', key: 'deliver_task_assign' },
    { label: '', key: 'deliver_task_receive' },
    { label: '', key: 'deliver_task_start,deliver_task_end,deliver_task_confirm' },
    { label: '', key: 'deliver_task_complete' },
  ],

  activeStatus: undefined,
  createTimeBegin: undefined,
  createTimeEnd: undefined,
  createTimeFilterPopoverVisible: false,
});

/**
 * @description 列表查询
 * @param {Number} page -当前页
 * @param {Number} pageSize -每页条数
 */
function queryList(page: number = 1, pageSize: number = 15) {
  if (!page && state.finished) return;
  state.loading = true;
  QUERY_APP_WO_DELIVER_LIST({
    comQuery: { page, pageSize },
    woDeliverDto: {
      releaseUserId: state.releaseUserId,
      assignModel: state.activeStatus === 'deliver_task_assign' ? 3 : 0,
    },
    statusList: state.activeStatus?.split(','),
    createTimeBegin: state.createTimeBegin,
    createTimeEnd: state.createTimeEnd,
  })
    .then((res) => {
      if (
        state.activePage >=
        (res.comQuery?.pageCount ||
          (res.comQuery?.totalCount as number) / (res.comQuery?.pageSize as number) ||
          1)
      ) {
        state.finished = true;
      }

      if (!res.woDeliverDto || !res.woDeliverDto.length) return;

      res.woDeliverDto.forEach((item) => state.list.push(item));

      state.activePage += 1;
      state.loading = false;
    })
    .catch(() => {
      state.loading = false;
    });
}

/**
 * @function 加载
 */
function onLoading() {
  if (state.finished) return;

  queryList(state.activePage);
}

onMounted(() => {
  state.activePage = 1;
  state.loading = true;
  state.finished = false;
  state.list = [];
  showLoading();

  if (params.pageType === 'report-history') {
    LOGIN_APP().then((res) => {
      state.releaseUserId = res.sysUserDto.uaaUserId;
      state.activeStatus = undefined;
      onLoading();
    });
  } else {
    params.pageType = 'default';
    state.releaseUserId = undefined;
    state.activeStatus = 'deliver_task_assign';
    eventCenter.on(getCurrentInstance().router?.onShow as string, () => {
      state.activePage = 1;
      state.loading = true;
      state.finished = false;
      state.list = [];
      queryListHeadAndList();
    });
  }

  setNavigationBarTitle({
    title: pageTypeObj[params.pageType],
  });
});

function queryListHeadAndList() {
  COUNT_APP_STATUS_QUANTITY({}).then((res) => {
    //待处理statusList参数固定是deliver_task_assign和deliver_task_receive
    const deliver_task_receive =
      res.statusQuantity.deliver_task_receive + res.statusQuantity.deliver_task_assign;
    //处理中statusList参数固定是task_start、task_end和task_confirm
    const task_process =
      res.statusQuantity.deliver_task_start +
      res.statusQuantity.deliver_task_end +
      res.statusQuantity.deliver_task_confirm;

    state.statusQuantity[1].label = `待接单(${
      deliver_task_receive > 99 ? '99+' : deliver_task_receive || 0
    })`;
    state.statusQuantity[2].label = `处理中(${task_process > 99 ? '99+' : task_process || 0})`;
    //完成statusList参数固定是task_complete
    state.statusQuantity[3].label = `已完成(${
      res.statusQuantity.deliver_task_complete > 99
        ? '99+'
        : res.statusQuantity.deliver_task_complete || 0
    })`;

    onLoading();
  });
}

/**
 * 显示计划时间
 */
function planTime(item: AppWoDeliver.Dto) {
  const planTimeStart = item.planTimeStart ? dayjs(item.planTimeStart).format('MM-DD HH:mm') : '-';
  const planTimeEnd = item.planTimeEnd ? dayjs(item.planTimeEnd).format('MM-DD HH:mm') : '-';
  return `${planTimeStart} 至 ${planTimeEnd}`;
}
</script>

<template>
  <view class="deliver-list app-page--1">
    <app-navbar :title="pageTypeObj[params.pageType]" />
    <nut-tabs
      v-if="params.pageType === 'default'"
      v-model="state.activeStatus"
      auto-height
      title-scroll
    >
      <template #titles>
        <div
          class="nut-tabs__titles-item"
          :key="item.key"
          @click="
            () => {
              state.activeStatus = item.key;
              state.activePage = 1;
              state.finished = false;
              state.list = [];
              state.createTimeBegin = undefined;
              state.createTimeEnd = undefined;
              onLoading();
            }
          "
          :class="{ active: state.activeStatus == item.key }"
          v-for="(item, index) in state.statusQuantity"
        >
          <image
            :src="IMG_ICON_DELIVER_ROB_TAB_TITLE"
            style="width: 70px; height: 13px"
            v-if="index === 0"
          />
          <span class="nut-tabs__titles-item__text" v-else>{{ item.label }}</span>
          <span class="nut-tabs__titles-item__line"></span>
        </div>
      </template>
      <nut-tab-pane v-for="item in state.statusQuantity" :key="item.key" :pane-key="item.key" />
    </nut-tabs>
    <nut-tabs
      v-else-if="params.pageType === 'report-history'"
      model-value="record"
      @click="
        ({ paneKey }) => {
          if (paneKey === 'push') {
            reLaunch({ url: '/pages/deliver/edit/index' });
          }
        }
      "
    >
      <nut-tab-pane title="新建运送" pane-key="push" />
      <nut-tab-pane title="申请记录" pane-key="record" />
    </nut-tabs>
    <scroll-view
      class="app-page__wrapper"
      :scroll-y="true"
      :lower-threshold="100"
      @scrolltolower="onLoading()"
    >
      <view class="deliver-list__wrapper">
        <view
          v-for="item in state.list"
          :key="item.id || ''"
          class="deliver-item"
          @click="
            navigateTo({
              url: `/pages/deliver/detail/index?id=${item.id}&from=${params.pageType}`,
            })
          "
        >
          <view class="deliver-item__header">
            <view class="deliver-item__header--left">
              <text class="deliver-item__code">{{ item.orderCode }}</text>
              <image v-if="item.urgency === 2" class="deliver-item__icon" :src="IMG_ICON_SPEED" />
              <view v-if="item.urgency === 3" class="deliver-item__icon-wrapper">
                <image class="deliver-item__icon" :src="IMG_ICON_SPEED" />
                <image class="deliver-item__icon" :src="IMG_ICON_SPEED" />
              </view>
              <text
                class="deliver-item__remain-time"
                v-if="params.pageType === 'default' && item.status !== 'deliver_task_complete'"
                >剩{{ formatSeconds(item.validDuration || 0) }}</text
              >
            </view>
            <view class="deliver-item__header--right">
              <text
                class="deliver-item__status"
                :style="{
                  color: item.status ? DELIVER_ORDER_STATUS_COLOR[item.status] : '#999',
                  backgroundColor: item.status
                    ? DELIVER_ORDER_STATUS_BG_COLOR[item.status]
                    : '#999',
                }"
              >
                {{ item.status ? DELIVER_ORDER_STATUS[item.status] : '-' }}
              </text>
            </view>
          </view>
          <view class="deliver-item__description">
            <text class="nut-ellipsis">{{ item.description }}</text>
          </view>
          <view>
            <text>运送路线:&nbsp;&nbsp;</text>
            <text>{{ `${item.areaNameStart || '-'} 至 ${item.areaNameEnd || '-'}` }}</text>
          </view>
          <view class="deliver-item__plan-time">
            <text>计划时间:&nbsp;&nbsp;</text>
            <text> {{ planTime(item) }}&nbsp;&nbsp; </text>
          </view>
          <view
            class="deliver-item__rush"
            v-if="
              item.status === 'deliver_task_assign' &&
              item.assignModel === 3 &&
              params.pageType === 'default'
            "
          >
            <image class="deliver-item__icon2" :src="IMG_ICON_DELIVER_ROB" />
          </view>
        </view>
      </view>

      <view class="app-page__list-tips">
        <text v-if="!state.list.length">暂无数据！</text>
        <text v-else-if="state.list.length && state.loading">加载中...</text>
        <text v-else-if="state.list.length && state.finished">加载完成!</text>
      </view>
    </scroll-view>
  </view>
</template>

<style lang="scss">
@import './index.scss';
</style>
